package com.kobeliu.entity;

/**
 * @Author: Kobe_Liu
 * @Date: 2021/12/11 18:37
 */
public class 二分排序 {
    public static void main(String[] args) {

        //初始化数组
        int[] nums = new int[]{1,2,3,4,5,6,7,8};
        //要查找的值
        int target = 3;

        //返回的是3对应序号的下标
        int index = binarySort(nums,target);

    }

    private static int binarySort(int[] nums, int target) {
        //异常处理，数组长度为零，那肯定不存在target
        //长度为1 ，也返回0
        if(nums.length<2) return 0;

        //两个指针，指针就是对应坐标的意思
        int left = 0;
        //为什么-1 因为计算机数组从0开始算，不是1
        int right = nums.length-1;

        while(left<=right){
            //就是（left+right)/2
            int mid = left + ((right-left)>>1);
            if(nums[mid]<target) left = mid+1;
            else if(nums[mid]>target) right = mid-1;
            else return left;
        }
        return -1; //-1就是代表没找到


    }
}
